package com.zy.garbage.controller;

import com.zy.garbage.enums.PermsEnum;
import com.zy.garbage.enums.ResultEnum;
import com.zy.garbage.exception.CommonException;
import com.zy.garbage.form.CreateAccountForm;
import com.zy.garbage.form.CreateGarbageForm;
import com.zy.garbage.service.GarbageService;
import com.zy.garbage.util.ResultUtil;
import com.zy.garbage.vo.GarbageManageVO;
import com.zy.garbage.vo.GarbageVO;
import com.zy.garbage.vo.ResultVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;


@RestController
@Slf4j
@RequestMapping("/garbage")
public class GarbageController extends BaseController {
    @Autowired
    private GarbageService garbageService;


    @GetMapping("/allGarbage")
    public ResultVO allUser() {
        try {
            GarbageManageVO garbageManageVO = garbageService.findAll();
            return ResultUtil.success(garbageManageVO);
        } catch (Exception e) {
            System.out.println(e.toString());
            return ResultUtil.error("查询失败");
        }

    }

    @PostMapping("/create")
    public ResultVO create(@Validated @RequestBody CreateGarbageForm createGarbageForm, HttpServletResponse response) {
        if (claims.get("perms").equals(PermsEnum.ADMIN.getPerms())) {
            try {
                GarbageVO garbageVO = garbageService.save(createGarbageForm);
                return ResultUtil.success(garbageVO);
            } catch (CommonException e) {
                throw new CommonException(500, e.getMessage());
            }
        }
        throw new CommonException(ResultEnum.NO_PERMS);
    }

    @PutMapping("/update")
    public ResultVO update(@Validated @RequestBody CreateGarbageForm createGarbageForm, HttpServletResponse response) {
        if (claims.get("perms").equals(PermsEnum.ADMIN.getPerms())) {
            try {
                GarbageVO garbageVO = garbageService.save(createGarbageForm);
                return ResultUtil.success(garbageVO);
            } catch (CommonException e) {
                throw new CommonException(500, "修改失败");
            }
        }
        throw new CommonException(ResultEnum.NO_PERMS);
    }

    @DeleteMapping("/delete/{garbageId}")
    public ResultVO delete(@PathVariable("garbageId") Integer garbageId, HttpServletResponse response) {
        if (claims.get("perms").equals(PermsEnum.ADMIN.getPerms())) {
            try {
                garbageService.delete(garbageId);
                return ResultUtil.success(null);
            } catch (CommonException e) {
                throw new CommonException(e.getCode(), e.getMessage());
            }
        }
        throw new CommonException(ResultEnum.NO_PERMS);
    }

}
